/*
 * View.cpp
 *
 *  Created on: 03/05/2011
 *      Author: DessaVida
 */

#include "View.h"
#include "util/Loader.h"


View::View() {
	sprite = NULL;
	state = 0;
	direction = 0;
	type = NORMAL;
	loadThings(0);
}

View::View(string normalSprite, string* attackSprite)
{
	sprite = NULL;
	state = 0;
	direction = 0;
	type = NORMAL;
	loadThings(0);
	this->normalSprite = normalSprite;
	if(attackSprite)
		this->attackSprite = *attackSprite;
	else
		this->attackSprite = "";
}

View::~View() {
	if(sprite)
		delete sprite;
}

void View::update(Model *model, Camera *camera)
{
	Point2D pos(model->position->getPoint());

	if(getCurrent() != sprite->GetCurrentAnimation()){
		sprite->StopAnimation();
		sprite->StartAnimation(getCurrent(), repeating);
	}
	sprite->SetPosition(pos.getX() + sprite->GetOffsetX(),pos.getY() + sprite->GetOffsetY());
	int xx = sprite->GetOffsetX();
	if(type == 1)
		xx = sprite->GetOffsetX();

	sprite->setRef(pos.getY() + sprite->GetReference());
	camera->addSprite(sprite);
}
/*
 * Getters and Setters
 */
Sprite *View::getSprite() const
{
    return sprite;
}

int View::getAnimation() const
{
    return n_animation;
}

void View::setAnimation(int n_animation)
{
    this->n_animation = n_animation;
}

void View::setSprite(Sprite *sprite)
{
    this->sprite = sprite;
}

int View::getCurrent()
{
	map<int, map<int, int> >::iterator it_dir = idList.find(direction);
	map<int, int>::iterator it_state = it_dir->second.find(state);
    return it_state->second;
}

void View::setState(int state)
{
    this->state = state;
}

void View::setDirection(Direction *dir)
{
	switch (dir->getDir()) {
		case SOUTH:
			this->direction = this->SOUTH;
			break;
		case EAST:
			this->direction = this->EAST;
			break;
		case NORTH:
			this->direction = this->NORTH;
			break;
		case WEST:
			this->direction = this->WEST;
			break;
		default:
			this->direction = 0;
			break;
	}
}

void View::setRepeating(bool repeating)
{
    this->repeating = repeating;
}

bool View::getRepeating() const
{
	return repeating;
}


void View::loadThings(int type)
{
	int n;
	if((unsigned) this->type == ATTACK){
		n = 3;
	}
	else{
		n = 5;
	}
	for(int i = 0; i < 4; i++){
		for(int j = 0; j < n; j++){
			idList[i][j] = j * 4 + i;
		}
	}

}


int View::getType() const
{
    return type;
}

void View::setType(int type)
{
	if(this->type != type){
		this->type = type;
		loadThings(type);
		if(!sprite)
			delete sprite;
		if(type == (int)ATTACK)
			sprite = Loader::loadSprite(attackSprite);
		else
			sprite = Loader::loadSprite(normalSprite);
	}
}

